package models;

import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;

import play.Logger;
import play.data.validation.CheckWith;
import play.data.validation.Equals;
import play.data.validation.MinSize;
import play.data.validation.Password;
import play.data.validation.Required;
import play.db.jpa.Blob;
import play.db.jpa.JPA;
import play.db.jpa.JPABase;
import play.db.jpa.Model;
import play.libs.Crypto;
/**
 * 用户
 * @author MrROY
 *
 */
@Entity
@Table(name="T_USER")
public class User extends Model {
	@Required
	@Column(name="username",nullable=false,unique=true)
	public String username;
	//用户头像文件名
	public Blob avatar;
	//头像文件名
	public String avatarFileName;
	@Required(message="请输入密码")
	@Equals(value="passwordConfirmation",message="两次输入的密码不一致")
	public String password;
	@Transient
	public String passwordConfirmation;
	@Required
	public boolean isValid = true;
	@OneToMany(mappedBy="user")
	public List<Story> stories;
	@OneToMany(mappedBy="user")
	public List<FavoriteStory> favoriteStories;
	@OneToMany(mappedBy="postUser")
	public List<Comment> comments;
	@OneToMany(mappedBy="owner")
	public List<FriendShip> owners;
	@OneToMany(mappedBy="friend")
	public List<FriendShip> friends;
	/**
	 * 验证用户输入的密码
	 * @param password
	 * @return
	 */
	public boolean loginWithPassword(String password){
		String input = Crypto.passwordHash(password);
		if(this.password.equals(input)){
			return true;
		}
		return false;
	}
	/**
	 * 判断用户名是否已存在
	 * @param username
	 * @return
	 */
	public static boolean isUsernameExists(String username){
		Long count = User.count("username = ? ",username);
		return count > 0 ? true:false;
	}
	/**
	 * 保存前对密码进行特殊处理
	 */
	public JPABase save(){
		return super.save();
	}
	@Override
	public void _delete() {
		if (this.avatar.getFile()!=null) {
			this.avatar.getFile().delete();
		}
		super._delete();
	}
}
